// 全局变量
let currentData = [];
let currentDataType = 'circles'; // 当前数据类型：'circles' 或 'experimental'
let coefficients = {};
let iterationResults = [];
let lineParameters = {};
let autoMode = true; // Auto模式默认开启

// 牛顿迭代相关变量
let currentTheta = 0;
let previousTheta = null; // 用于跟踪上一次的theta值
let currentIteration = 0;
let isIterating = false;
let targetPrecision = 10;

// 统一的Plotly导出与样式配置（300DPI）
const PLOT_SCALE = 3.125; // 300/96 ≈ 3.125
const FONT_FAMILY = 'SimSun, "Times New Roman", serif';

// 仅用于导出：克隆并放大字体/线宽/标记尺寸，不改变页面显示
function __cloneDeep(obj) { return JSON.parse(JSON.stringify(obj)); }
function __scaleFontsInLayout(layout, factor, family) {
    const out = __cloneDeep(layout || {});
    // 深度遍历所有font字段
    (function walk(node) {
        if (!node || typeof node !== 'object') return;
        if (node.font && typeof node.font === 'object') {
            const f = node.font;
            if (typeof f.size === 'number') f.size = f.size * factor;
            f.family = family;
        }
        // 轴刻度字体 tickfont 也需要放大
        if (node.tickfont && typeof node.tickfont === 'object') {
            const tf = node.tickfont;
            if (typeof tf.size === 'number') tf.size = tf.size * factor;
            tf.family = family;
        }
        // 线条粗细类属性放大
        if (typeof node.linewidth === 'number') node.linewidth = node.linewidth * factor;
        if (typeof node.gridwidth === 'number') node.gridwidth = node.gridwidth * factor;
        if (typeof node.borderwidth === 'number') node.borderwidth = node.borderwidth * factor;
        if (typeof node.zerolinewidth === 'number') node.zerolinewidth = node.zerolinewidth * factor;
        if (typeof node.tickwidth === 'number') node.tickwidth = node.tickwidth * factor;
        for (const k in node) {
            if (k === 'font') continue;
            const v = node[k];
            if (v && typeof v === 'object') walk(v);
        }
    })(out);
    if (!out.font) out.font = { family: family };
    // 导出时为最左和最下轴预留额外空间，并把对应轴标题外移，避免与刻度数字重叠
    const EXTRA_MARGIN = 30; // 额外空白像素
    const TITLE_STANDOFF = 24; // 轴标题与刻度间距（不改变字体大小）
    if (!out.margin) out.margin = {};
    out.margin.l = (out.margin.l || 0) + EXTRA_MARGIN;
    out.margin.b = (out.margin.b || 0) + EXTRA_MARGIN;

    const xKeys = Object.keys(out).filter(k => k === 'xaxis' || /^xaxis\d+$/.test(k));
    const yKeys = Object.keys(out).filter(k => k === 'yaxis' || /^yaxis\d+$/.test(k));

    // 底部x轴标题外移
    for (const xk of xKeys) {
        const xa = out[xk];
        if (!xa || typeof xa !== 'object') continue;
        const anchor = xa.anchor || 'y';
        const yKey = anchor === 'y' ? 'yaxis' : (anchor && anchor.startsWith('y') ? ('yaxis' + anchor.slice(1)) : null);
        const ya = yKey ? out[yKey] : null;
        let isBottom = false;
        if (ya && Array.isArray(ya.domain)) {
            const ymin = ya.domain[0];
            if (typeof ymin === 'number' && ymin <= 0.02) isBottom = true;
        }
        if (isBottom) {
            if (typeof xa.title === 'string') xa.title = { text: xa.title };
            if (!xa.title) xa.title = {};
            if (typeof xa.title.standoff !== 'number' || xa.title.standoff < TITLE_STANDOFF) {
                xa.title.standoff = TITLE_STANDOFF;
            }
        }
    }

    // 最左y轴标题外移
    for (const yk of yKeys) {
        const ya = out[yk];
        if (!ya || typeof ya !== 'object') continue;
        const anchor = ya.anchor || 'x';
        const xKey = anchor === 'x' ? 'xaxis' : (anchor && anchor.startsWith('x') ? ('xaxis' + anchor.slice(1)) : null);
        const xa = xKey ? out[xKey] : null;
        let isLeft = false;
        if (xa && Array.isArray(xa.domain)) {
            const xmin = xa.domain[0];
            if (typeof xmin === 'number' && xmin <= 0.02) isLeft = true;
        }
        if (isLeft) {
            if (typeof ya.title === 'string') ya.title = { text: ya.title };
            if (!ya.title) ya.title = {};
            if (typeof ya.title.standoff !== 'number' || ya.title.standoff < TITLE_STANDOFF) {
                ya.title.standoff = TITLE_STANDOFF;
            }
        }
    }
    return out;
}
function __buildExportFigure(gd, factor = PLOT_SCALE, family = FONT_FAMILY) {
    const data = (gd.data || []).map(trace => {
        const t = __cloneDeep(trace);
        if (t.line && typeof t.line.width === 'number') t.line.width = t.line.width * factor;
        if (t.marker && typeof t.marker.size === 'number') t.marker.size = t.marker.size * factor;
        if (t.marker && t.marker.line && typeof t.marker.line.width === 'number') t.marker.line.width = t.marker.line.width * factor;
        if (t.textfont && typeof t.textfont.size === 'number') t.textfont.size = t.textfont.size * factor;
        return t;
    });
    const layout = __scaleFontsInLayout(gd.layout, factor, family);
    return { data, layout };
}

const plotConfig = {
    responsive: true,
    displaylogo: false,
    displayModeBar: true,
    // 替换默认下载按钮，导出时放大元素并统一字体（页面显示不变）
    modeBarButtonsToRemove: ['toImage'],
    modeBarButtonsToAdd: [{
        name: 'Download plot as PNG',
        title: 'Download plot as PNG (300 DPI)',
        icon: (typeof Plotly !== 'undefined' && Plotly.Icons && Plotly.Icons.camera) ? Plotly.Icons.camera : undefined,
        click: function(gd) {
            const fig = __buildExportFigure(gd, PLOT_SCALE, FONT_FAMILY);
            const opts = { format: 'png', width: 1800, height: 1350, scale: PLOT_SCALE };
            Plotly.toImage(fig, opts).then(url => {
                const a = document.createElement('a');
                a.href = url;
                a.download = 'mohr_circle_300dpi.png';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        }
    }],
    toImageButtonOptions: {
        format: 'png',
        filename: 'mohr_circle_300dpi',
        width: 1800,
        height: 1350,
        scale: PLOT_SCALE
    }
};

// 尺寸缩放工具函数
function scaledInt(value) {
    return Math.round(value * PLOT_SCALE);
}
function scaledFloat(value) {
    return parseFloat((value * PLOT_SCALE).toFixed(3));
}

// 检查theta值是否发生变化，如果变化且在auto模式下则触发计算直线参数
function checkThetaChangeAndTriggerCalculation() {
    // 检查theta值是否发生变化
    if (previousTheta !== null && Math.abs(currentTheta - previousTheta) < 1e-10) {
        // theta值没有变化，不触发计算
        return;
    }

    // 更新previousTheta
    previousTheta = currentTheta;

    // 如果在auto模式下且有系数数据，触发计算直线参数
    if (autoMode && Object.keys(coefficients).length > 0) {
        setTimeout(() => {
            calculateLineParameters();
        }, 500); // 延迟500ms确保界面更新完成
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 生成随机初始θ值
    generateRandomInitialTheta();

    // 数据类型切换事件
    document.getElementById('dataType').addEventListener('change', function() {
        toggleInputType();
    });

    // θ范围变化事件
    document.getElementById('thetaMin').addEventListener('input', function() {
        // 检查当前初始θ值是否在新范围内
        checkAndUpdateInitialTheta();

        if (Object.keys(coefficients).length > 0) {
            updateFunctionPlot(currentTheta);
        }
    });

    document.getElementById('thetaMax').addEventListener('input', function() {
        // 检查当前初始θ值是否在新范围内
        checkAndUpdateInitialTheta();

        if (Object.keys(coefficients).length > 0) {
            updateFunctionPlot(currentTheta);
        }
    });

    // 初始θ值变化事件
    document.getElementById('initialTheta').addEventListener('input', function() {
        if (!isIterating && Object.keys(coefficients).length > 0) {
            const newTheta = parseFloat(this.value) || 0;
            currentTheta = newTheta; // 更新currentTheta
            updateFunctionPlot(newTheta);

            // 检查theta值变化并触发计算直线参数
            checkThetaChangeAndTriggerCalculation();
        }
    });

    // 初始化图表
    initializePlots();
});

// 切换输入类型
function toggleInputType() {
    const dataType = document.getElementById('dataType').value;
    const circleInputs = document.getElementById('circleInputs');
    const experimentalInputs = document.getElementById('experimentalInputs');
    
    if (dataType === 'circles') {
        circleInputs.style.display = 'block';
        experimentalInputs.style.display = 'none';
    } else {
        circleInputs.style.display = 'none';
        experimentalInputs.style.display = 'block';
    }
}

// 添加手动数据
async function addManualData() {
    const dataType = document.getElementById('dataType').value;
    let data = { type: dataType };
    
    if (dataType === 'circles') {
        data.x = parseFloat(document.getElementById('circleX').value);
        data.y = parseFloat(document.getElementById('circleY').value);
        data.r = parseFloat(document.getElementById('circleR').value);
        
        if (isNaN(data.x) || isNaN(data.y) || isNaN(data.r) || data.r <= 0) {
            showAlert('请输入有效的数值，半径必须大于0', 'danger');
            return;
        }
    } else {
        data.confining_pressure = parseFloat(document.getElementById('confiningPressure').value);
        data.compressive_strength = parseFloat(document.getElementById('compressiveStrength').value);
        
        if (isNaN(data.confining_pressure) || isNaN(data.compressive_strength) || 
            data.confining_pressure < 0 || data.compressive_strength < 0) {
            showAlert('请输入有效的数值，围压和抗压强度必须大于等于0', 'danger');
            return;
        }
    }
    
    try {
        const response = await fetch('/api/add_manual_data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentData = result.data;
            currentDataType = result.data_type || 'circles';
            updateDataTable();
            updateMohrCirclePlot();
            clearInputFields();
            showAlert(result.message, 'success');
            updateProgress(25);

            // Auto模式：自动触发计算系数
            if (autoMode && currentData.length >= 2) {
                setTimeout(() => {
                    calculateCoefficients();
                }, 500); // 延迟500ms确保界面更新完成
            }
        } else {
            showAlert(result.error, 'danger');
        }
    } catch (error) {
        showAlert('添加数据时发生错误: ' + error.message, 'danger');
    }
}

// 上传Excel文件
async function uploadExcel() {
    const fileInput = document.getElementById('excelFile');
    const file = fileInput.files[0];
    
    if (!file) {
        showAlert('请选择一个Excel文件', 'warning');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
        const response = await fetch('/api/upload_excel', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentData = result.data;
            currentDataType = result.data_type || 'circles';
            updateDataTable();
            updateMohrCirclePlot();
            showAlert(result.message, 'success');
            updateProgress(25);

            // Auto模式：自动触发计算系数
            if (autoMode && currentData.length >= 2) {
                setTimeout(() => {
                    calculateCoefficients();
                }, 500); // 延迟500ms确保界面更新完成
            }
        } else {
            showAlert(result.error, 'danger');
        }
    } catch (error) {
        showAlert('上传文件时发生错误: ' + error.message, 'danger');
    }
}

// 清空所有数据
async function clearAllData() {
    try {
        const response = await fetch('/api/clear_data', {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentData = [];
            currentDataType = 'circles'; // 重置为默认类型
            coefficients = {};
            iterationResults = [];
            lineParameters = {};
            updateDataTable();
            updateMohrCirclePlot();
            clearResults();
            showAlert(result.message, 'info');
            updateProgress(0);
        }
    } catch (error) {
        showAlert('清空数据时发生错误: ' + error.message, 'danger');
    }
}

// 更新数据表格表头
function updateTableHeader() {
    const thead = document.querySelector('.data-table thead tr');
    if (currentDataType === 'experimental') {
        thead.innerHTML = `
            <th>序号</th>
            <th>围压</th>
            <th>抗压强度</th>
        `;
    } else {
        thead.innerHTML = `
            <th>序号</th>
            <th>X坐标</th>
            <th>Y坐标</th>
            <th>半径</th>
        `;
    }
}

// 更新数据表格
function updateDataTable() {
    updateTableHeader();

    const tbody = document.getElementById('dataTableBody');
    tbody.innerHTML = '';

    currentData.forEach((item, index) => {
        const row = tbody.insertRow();
        row.insertCell(0).textContent = index + 1;

        if (currentDataType === 'experimental' && item.confining_pressure !== undefined && item.compressive_strength !== undefined) {
            // 显示原始的围压和抗压强度数据
            row.insertCell(1).textContent = item.confining_pressure.toFixed(4);
            row.insertCell(2).textContent = item.compressive_strength.toFixed(4);
        } else {
            // 显示圆数据
            row.insertCell(1).textContent = item.x.toFixed(4);
            row.insertCell(2).textContent = item.y.toFixed(4);
            row.insertCell(3).textContent = item.r.toFixed(4);
        }
    });
}

// 更新莫尔圆绘图
function updateMohrCirclePlot() {
    if (currentData.length === 0) {
        Plotly.purge('mohrCirclePlot');
        return;
    }

    const traces = [];

    // 绘制每个圆
    currentData.forEach((circle, index) => {
        const theta = Array.from({length: 101}, (_, i) => i * 2 * Math.PI / 100);
        const x = theta.map(t => circle.x + circle.r * Math.cos(t));
        const y = theta.map(t => circle.y + circle.r * Math.sin(t));

        traces.push({
            x: x,
            y: y,
            type: 'scatter',
            mode: 'lines',
            name: `圆 ${index + 1}`,
            line: { width: 2 }
        });

        // 添加圆心
        traces.push({
            x: [circle.x],
            y: [circle.y],
            type: 'scatter',
            mode: 'markers',
            name: `圆心 ${index + 1}`,
            marker: { size: 8, color: 'black' },
            showlegend: false
        });
    });

    // 添加包络线（如果已计算）
    if (Object.keys(lineParameters).length > 0) {
        addEnvelopeLineToPlot(traces);
    }
    
    const layout = {
        title: '莫尔圆图',
        xaxis: { title: 'σ (MPa)', scaleanchor: 'y' },
        yaxis: { title: 'τ (MPa)' },
        aspectratio: { x: 1, y: 1 },
        font: { family: 'Times New Roman', size: 12 },
        margin: { t: 60, b: 60, l: 70, r: 30 },
        height: 600
    };
    
    Plotly.newPlot('mohrCirclePlot', traces, layout, plotConfig);
}

// 添加包络线到莫尔圆图
function addEnvelopeLineToPlot(traces) {
    if (!lineParameters || Object.keys(lineParameters).length === 0) {
        return;
    }

    // 计算图的范围，基于现有圆的数据
    let minX = Infinity, maxX = -Infinity;
    let minY = Infinity, maxY = -Infinity;

    currentData.forEach(circle => {
        minX = Math.min(minX, circle.x - circle.r);
        maxX = Math.max(maxX, circle.x + circle.r);
        minY = Math.min(minY, circle.y - circle.r);
        maxY = Math.max(maxY, circle.y + circle.r);
    });

    // 扩展范围以确保直线完全可见
    const rangeX = maxX - minX;
    const rangeY = maxY - minY;
    const extendX = rangeX * 0.3; // 扩展30%以确保直线可见
    const extendY = rangeY * 0.3;

    minX -= extendX;
    maxX += extendX;
    minY -= extendY;
    maxY += extendY;

    // 使用直线方程 y = mx + c 生成直线点
    // 这里的intercept实际上是c值，即y轴截距
    const slope = lineParameters.slope;
    const intercept = lineParameters.intercept;

    const lineX = [];
    const lineY = [];

    // 生成足够的点来绘制直线
    const numPoints = 200;
    for (let i = 0; i <= numPoints; i++) {
        const x = minX + (maxX - minX) * i / numPoints;
        const y = slope * x + intercept;

        // 检查点是否在合理范围内
        if (y >= minY && y <= maxY) {
            lineX.push(x);
            lineY.push(y);
        }
    }

    // 如果没有足够的点，尝试通过Y值范围生成点
    if (lineX.length < 2 && Math.abs(slope) > 1e-10) {
        lineX.length = 0;
        lineY.length = 0;

        for (let i = 0; i <= numPoints; i++) {
            const y = minY + (maxY - minY) * i / numPoints;
            const x = (y - intercept) / slope;

            if (x >= minX && x <= maxX) {
                lineX.push(x);
                lineY.push(y);
            }
        }
    }

    // 只有当有足够的点时才添加直线
    if (lineX.length >= 2) {
        traces.push({
            x: lineX,
            y: lineY,
            type: 'scatter',
            mode: 'lines',
            name: '包络线',
            line: {
                color: '#FF0000',
                width: 2,
                dash: 'solid'
            },
            showlegend: true
        });
    }
}

// 计算系数
async function calculateCoefficients() {
    if (currentData.length === 0) {
        showAlert('请先输入数据', 'warning');
        return;
    }
    
    try {
        const response = await fetch('/api/calculate_coefficients', {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.success) {
            coefficients = result.coefficients;
            displayCoefficients();
            showAlert('系数计算完成', 'success');
            updateProgress(50);

            // 自动重置牛顿迭代并生成随机初始θ值
            generateRandomInitialTheta();
            resetNewton();
        } else {
            showAlert(result.error, 'danger');
        }
    } catch (error) {
        showAlert('计算系数时发生错误: ' + error.message, 'danger');
    }
}

// 显示系数结果
function displayCoefficients() {
    const resultDiv = document.getElementById('coefficientsResult');
    resultDiv.innerHTML = `
        <h6>计算结果:</h6>
        <div class="row">
            <div class="col-md-6">
                <p><strong>A:</strong> ${coefficients.A.toFixed(6)}</p>
                <p><strong>B:</strong> ${coefficients.B.toFixed(6)}</p>
                <p><strong>C:</strong> ${coefficients.C.toFixed(6)}</p>
                <p><strong>D:</strong> ${coefficients.D.toFixed(6)}</p>
            </div>
            <div class="col-md-6">
                <p><strong>x平均:</strong> ${coefficients.x_mean.toFixed(6)}</p>
                <p><strong>y平均:</strong> ${coefficients.y_mean.toFixed(6)}</p>
                <p><strong>r平均:</strong> ${coefficients.r_mean.toFixed(6)}</p>
            </div>
        </div>
    `;

    // 系数计算完成后，绘制f(θ)函数图像
    updateFunctionPlot();
}

// 计算f(θ)函数值
function calculateF(theta) {
    if (Object.keys(coefficients).length === 0) return 0;

    const A = coefficients.A;
    const B = coefficients.B;
    const C = coefficients.C;
    const D = coefficients.D;

    return A * Math.sin(2 * theta) + B * Math.cos(2 * theta) +
           C * Math.sin(theta) + D * Math.cos(theta);
}

// 更新f(θ)函数图像
function updateFunctionPlot(highlightTheta = null) {
    if (Object.keys(coefficients).length === 0) {
        return;
    }

    const thetaMin = parseFloat(document.getElementById('thetaMin').value) || 0;
    const thetaMax = parseFloat(document.getElementById('thetaMax').value) || Math.PI/2;

    // 生成θ值数组
    const thetaValues = [];
    const fValues = [];
    const numPoints = 200;

    for (let i = 0; i <= numPoints; i++) {
        const theta = thetaMin + (thetaMax - thetaMin) * i / numPoints;
        thetaValues.push(theta);
        fValues.push(calculateF(theta));
    }

    // 创建函数曲线（期刊标准）
    const trace1 = {
        x: thetaValues,
        y: fValues,
        type: 'scatter',
        mode: 'lines',
        name: 'f(θ)',
        line: {
            color: '#000000',  // 黑色线条，符合期刊标准
            width: 1.5
        },
        showlegend: false
    };

    const traces = [trace1];

    // 添加零线
    const zeroLine = {
        x: [thetaMin, thetaMax],
        y: [0, 0],
        type: 'scatter',
        mode: 'lines',
        name: 'y = 0',
        line: {
            color: '#000000',
            width: 1,
            dash: 'dash'
        },
        showlegend: false
    };
    traces.push(zeroLine);

    // 添加高亮点
    if (highlightTheta !== null) {
        const fTheta = calculateF(highlightTheta);
        const highlightPoint = {
            x: [highlightTheta],
            y: [fTheta],
            type: 'scatter',
            mode: 'markers',
            name: `θ = ${highlightTheta.toFixed(5)}`,
            marker: {
                color: '#FF0000',
                size: 8,
                symbol: 'circle',
                line: {
                    color: '#000000',
                    width: 1
                }
            },
            showlegend: true
        };
        traces.push(highlightPoint);
    }

    const layout = {
        title: {
            text: 'f(θ) = A·sin(2θ) + B·cos(2θ) + C·sin(θ) + D·cos(θ)',
            font: {
                family: 'Times New Roman',
                size: 12,
                color: '#000000'
            },
            x: 0.5,
            xanchor: 'center'
        },
        xaxis: {
            title: {
                text: 'θ (radians)',
                font: {
                    family: 'Times New Roman',
                    size: 12,
                    color: '#000000'
                }
            },
            range: [thetaMin, thetaMax],
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: {
                family: 'Times New Roman',
                size: 10,
                color: '#000000'
            }
        },
        yaxis: {
            title: {
                text: 'f(θ)',
                font: {
                    family: 'Times New Roman',
                    size: 12,
                    color: '#000000'
                }
            },
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: {
                family: 'Times New Roman',
                size: 10,
                color: '#000000'
            }
        },
        font: {
            family: 'Times New Roman',
            size: 10,
            color: '#000000'
        },
        margin: { t: 80, b: 80, l: 80, r: 80 },
        showlegend: true,
        legend: {
            x: 0.02,
            y: 0.98,
            font: {
                family: 'Times New Roman',
                size: 10,
                color: '#000000'
            },
            bgcolor: 'rgba(255,255,255,0.8)',
            bordercolor: '#000000',
            borderwidth: 1
        },
        plot_bgcolor: 'white',
        paper_bgcolor: 'white',
        height: 450
    };
    
    Plotly.newPlot('functionPlot', traces, layout, plotConfig);
}

// 检查并更新初始θ值是否在范围内
function checkAndUpdateInitialTheta() {
    const thetaMinInput = document.getElementById('thetaMin');
    const thetaMaxInput = document.getElementById('thetaMax');
    const initialThetaInput = document.getElementById('initialTheta');

    if (!thetaMinInput || !thetaMaxInput || !initialThetaInput) {
        return;
    }

    const minTheta = parseFloat(thetaMinInput.value) || 0;
    const maxTheta = parseFloat(thetaMaxInput.value) || Math.PI / 2;
    const currentInitialTheta = parseFloat(initialThetaInput.value) || 0;

    // 如果当前初始θ值超出范围，重新生成
    if (currentInitialTheta < minTheta || currentInitialTheta > maxTheta) {
        generateRandomInitialTheta();
    }
}

// 生成随机初始θ值 - 始终在第一象限内随机生成，也要在用户设置的范围内
function generateRandomInitialTheta() {
    // 获取用户设置的θ范围
    const thetaMinInput = document.getElementById('thetaMin');
    const thetaMaxInput = document.getElementById('thetaMax');

    let minTheta = 0;
    let maxTheta = Math.PI / 2; // 默认值

    if (thetaMinInput && thetaMaxInput) {
        minTheta = parseFloat(thetaMinInput.value) || 0;
        maxTheta = parseFloat(thetaMaxInput.value) || Math.PI / 2;
    }

    // 确保范围在第一象限内 (0 < θ < π/2)
    const firstQuadrantMin = 0.001; // 避免θ=0
    const firstQuadrantMax = Math.PI / 2 - 0.001; // 避免θ=π/2

    // 将用户设置的范围约束在第一象限内
    minTheta = Math.max(minTheta, firstQuadrantMin);
    maxTheta = Math.min(maxTheta, firstQuadrantMax);

    // 确保范围有效
    if (minTheta >= maxTheta) {
        // 如果用户设置的范围无效，使用默认的第一象限范围
        minTheta = firstQuadrantMin;
        maxTheta = firstQuadrantMax;
    }

    // 在约束后的θ范围内生成随机值
    const randomTheta = minTheta + Math.random() * (maxTheta - minTheta);

    // 更新输入框的值
    const initialThetaInput = document.getElementById('initialTheta');
    if (initialThetaInput) {
        initialThetaInput.value = randomTheta.toFixed(6);
    }

    // 更新currentTheta，这会触发theta值变化检查
    currentTheta = randomTheta;
}

// 重置牛顿迭代
function resetNewton() {
    // 每次重置都生成新的随机θ值
    generateRandomInitialTheta();

    currentTheta = parseFloat(document.getElementById('initialTheta').value) || 0;
    currentIteration = 0;
    isIterating = false;
    iterationResults = [];

    // 清空表格
    document.getElementById('iterationTableBody').innerHTML = '';

    // 重置按钮状态
    document.getElementById('stepButton').disabled = false;

    // 更新函数图像，显示初始点
    updateFunctionPlot(currentTheta);

    // 清空收敛图
    Plotly.purge('newtonPlot');

    // 检查theta值变化并触发计算直线参数
    checkThetaChangeAndTriggerCalculation();

    showAlert('迭代状态已重置，θ值已更新', 'info');
}

// 牛顿迭代求解（自动迭代）
async function solveNewton() {
    if (Object.keys(coefficients).length === 0) {
        showAlert('请先计算系数', 'warning');
        return;
    }

    const initialTheta = parseFloat(document.getElementById('initialTheta').value);
    const precision = parseInt(document.getElementById('precision').value);

    if (isNaN(initialTheta) || isNaN(precision) || precision < 1 || precision > 64) {
        showAlert('请输入有效的初始θ值和精度', 'warning');
        return;
    }

    // 重置状态
    resetNewton();

    try {
        const response = await fetch('/api/newton_iteration', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                theta_0: initialTheta,
                precision: precision
            })
        });

        const result = await response.json();

        if (result.success) {
            iterationResults = result.iterations;
            currentTheta = result.final_theta;
            currentIteration = iterationResults.length;
            isIterating = false;

            displayIterationResults();
            updateNewtonPlot();
            updateFunctionPlot(currentTheta);

            // 禁用逐次迭代按钮
            document.getElementById('stepButton').disabled = true;

            // 检查theta值是否在第一象限（仅警告，不阻止计算）
            if (currentTheta <= 0 || currentTheta >= Math.PI / 2) {
                showAlert('自动迭代完成，但θ值超出第一象限范围（0 < θ < π/2），结果可能需要谨慎解释', 'warning');
            } else {
                showAlert('自动迭代完成', 'success');
            }
            updateProgress(75);

            // Auto模式：检查theta值变化并触发计算直线参数
            checkThetaChangeAndTriggerCalculation();
        } else {
            showAlert(result.error, 'danger');
        }
    } catch (error) {
        showAlert('自动迭代时发生错误: ' + error.message, 'danger');
    }
}

// 逐次迭代
async function stepNewton() {
    if (Object.keys(coefficients).length === 0) {
        showAlert('请先计算系数', 'warning');
        return;
    }

    const precision = parseInt(document.getElementById('precision').value);
    if (isNaN(precision) || precision < 1 || precision > 64) {
        showAlert('请输入有效的精度', 'warning');
        return;
    }

    // 如果是第一次迭代，初始化
    if (currentIteration === 0) {
        currentTheta = parseFloat(document.getElementById('initialTheta').value) || 0;
        iterationResults = [];
        isIterating = true;
        targetPrecision = precision;
    }

    try {
        const response = await fetch('/api/newton_step', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                current_theta: currentTheta,
                iteration: currentIteration,
                precision: targetPrecision
            })
        });

        const result = await response.json();

        if (result.success) {
            // 更新当前状态
            currentTheta = result.new_theta;
            currentIteration++;

            // 添加到迭代结果
            const iterationData = {
                iteration: currentIteration,
                theta: result.new_theta,
                f_theta: result.f_theta,
                delta: result.delta,
                converged: result.converged
            };
            iterationResults.push(iterationData);

            // 更新显示
            displayIterationResults();
            updateNewtonPlot();
            updateFunctionPlot(currentTheta);

            // Auto模式：检查theta值变化并触发计算直线参数（每次迭代都检查）
            checkThetaChangeAndTriggerCalculation();

            // 检查是否收敛
            if (result.converged) {
                document.getElementById('stepButton').disabled = true;
                isIterating = false;

                // 检查theta值是否在第一象限（仅警告，不阻止计算）
                if (currentTheta <= 0 || currentTheta >= Math.PI / 2) {
                    showAlert(`迭代收敛！最终θ = ${currentTheta.toFixed(8)}，但θ值超出第一象限范围，结果可能需要谨慎解释`, 'warning');
                } else {
                    showAlert(`迭代收敛！最终θ = ${currentTheta.toFixed(8)}`, 'success');
                }
                updateProgress(75);
            }
        } else {
            showAlert(result.error, 'danger');
            document.getElementById('stepButton').disabled = true;
            isIterating = false;
        }
    } catch (error) {
        showAlert('逐次迭代时发生错误: ' + error.message, 'danger');
        document.getElementById('stepButton').disabled = true;
        isIterating = false;
    }
}

// 显示迭代结果
function displayIterationResults() {
    const tbody = document.getElementById('iterationTableBody');
    tbody.innerHTML = '';

    iterationResults.forEach(result => {
        const row = tbody.insertRow();
        row.insertCell(0).textContent = result.iteration;
        row.insertCell(1).textContent = result.theta.toFixed(8);
        row.insertCell(2).textContent = result.f_theta.toExponential(4);
        row.insertCell(3).textContent = result.delta.toExponential(4);

        // 如果收敛，高亮显示
        if (result.converged) {
            row.classList.add('table-success');
        }
    });
}

// 更新牛顿迭代图 - 4个子图显示（期刊标准）
function updateNewtonPlot() {
    if (iterationResults.length === 0) return;

    const iterations = iterationResults.map(r => r.iteration);
    const thetas = iterationResults.map(r => r.theta);
    const fThetas = iterationResults.map(r => {
        const val = Math.abs(r.f_theta);
        return val > 0 ? val : 1e-16; // 避免log(0)，修复图二的bug
    });
    const deltas = iterationResults.map(r => {
        const val = Math.abs(r.delta);
        return val > 0 ? val : 1e-16; // 避免log(0)
    });
    const negLogDeltas = iterationResults.map(r => {
        const delta = Math.abs(r.delta);
        return delta > 0 ? -Math.log10(delta) : 16;
    });

    // 子图1: θ随迭代次数变化
    const trace1 = {
        x: iterations,
        y: thetas,
        type: 'scatter',
        mode: 'lines+markers',
        name: 'θ',
        line: { color: '#000000', width: 1.5 },
        marker: {
            color: '#000000',
            size: 4,
            symbol: 'circle'
        },
        xaxis: 'x1',
        yaxis: 'y1'
    };

    // 子图2: |f(θ)|随迭代次数变化（修复bug）
    const trace2 = {
        x: iterations,
        y: fThetas,
        type: 'scatter',
        mode: 'lines+markers',
        name: '|f(θ)|',
        line: { color: '#000000', width: 1.5 },
        marker: {
            color: '#000000',
            size: 4,
            symbol: 'square'
        },
        xaxis: 'x2',
        yaxis: 'y2'
    };

    // 子图3: |Δθ|随迭代次数变化
    const trace3 = {
        x: iterations,
        y: deltas,
        type: 'scatter',
        mode: 'lines+markers',
        name: '|Δθ|',
        line: { color: '#000000', width: 1.5 },
        marker: {
            color: '#000000',
            size: 4,
            symbol: 'diamond'
        },
        xaxis: 'x3',
        yaxis: 'y3'
    };

    // 子图4: -log₁₀(|Δθ|)随迭代次数变化
    const trace4 = {
        x: iterations,
        y: negLogDeltas,
        type: 'scatter',
        mode: 'lines+markers',
        name: '-log₁₀(|Δθ|)',
        line: { color: '#000000', width: 1.5 },
        marker: {
            color: '#000000',
            size: 4,
            symbol: 'triangle-up'
        },
        xaxis: 'x4',
        yaxis: 'y4'
    };

    const layout = {
        title: {
            text: '',  // 移除总标题，符合期刊标准
            font: { family: 'Times New Roman', size: 12 }
        },

        // 子图(a) - 左上
        xaxis1: {
            domain: [0, 0.42],
            anchor: 'y1',
            title: {
                text: 'Iteration number',
                font: { family: 'Times New Roman', size: 12 }
            },
            dtick: 1,
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },
        yaxis1: {
            domain: [0.58, 1],
            anchor: 'x1',
            title: {
                text: 'θ',
                font: { family: 'Times New Roman', size: 12 }
            },
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },

        // 子图(b) - 右上
        xaxis2: {
            domain: [0.58, 1],
            anchor: 'y2',
            title: {
                text: 'Iteration number',
                font: { family: 'Times New Roman', size: 12 }
            },
            dtick: 1,
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },
        yaxis2: {
            domain: [0.58, 1],
            anchor: 'x2',
            title: {
                text: '|f(θ)|',
                font: { family: 'Times New Roman', size: 12 }
            },
            type: 'log',
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },

        // 子图(c) - 左下
        xaxis3: {
            domain: [0, 0.42],
            anchor: 'y3',
            title: {
                text: 'Iteration number',
                font: { family: 'Times New Roman', size: 12 }
            },
            dtick: 1,
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },
        yaxis3: {
            domain: [0, 0.42],
            anchor: 'x3',
            title: {
                text: '|Δθ|',
                font: { family: 'Times New Roman', size: 12 }
            },
            type: 'log',
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },

        // 子图(d) - 右下
        xaxis4: {
            domain: [0.58, 1],
            anchor: 'y4',
            title: {
                text: 'Iteration number',
                font: { family: 'Times New Roman', size: 12 }
            },
            dtick: 1,
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },
        yaxis4: {
            domain: [0, 0.42],
            anchor: 'x4',
            title: {
                text: '-log₁₀(|Δθ|)',
                font: { family: 'Times New Roman', size: 12 }
            },
            showgrid: true,
            gridcolor: '#e0e0e0',
            gridwidth: 0.5,
            zeroline: false,
            linecolor: '#000000',
            linewidth: 1,
            mirror: true,
            ticks: 'outside',
            tickfont: { family: 'Times New Roman', size: 10 }
        },

        font: { family: 'Times New Roman', size: 10 },
        margin: { t: 60, b: 80, l: 80, r: 80 },
        showlegend: false,
        plot_bgcolor: 'white',
        paper_bgcolor: 'white',
        height: 600,
        // 添加子图标签 (a), (b), (c), (d)
        annotations: [
            {
                text: '(a)',
                x: 0.02,
                y: 0.98,
                xref: 'paper',
                yref: 'paper',
                showarrow: false,
                font: { family: 'Times New Roman', size: 12, color: 'black' },
                xanchor: 'left',
                yanchor: 'top'
            },
            {
                text: '(b)',
                x: 0.60,
                y: 0.98,
                xref: 'paper',
                yref: 'paper',
                showarrow: false,
                font: { family: 'Times New Roman', size: 12, color: 'black' },
                xanchor: 'left',
                yanchor: 'top'
            },
            {
                text: '(c)',
                x: 0.02,
                y: 0.40,
                xref: 'paper',
                yref: 'paper',
                showarrow: false,
                font: { family: 'Times New Roman', size: 12, color: 'black' },
                xanchor: 'left',
                yanchor: 'top'
            },
            {
                text: '(d)',
                x: 0.60,
                y: 0.40,
                xref: 'paper',
                yref: 'paper',
                showarrow: false,
                font: { family: 'Times New Roman', size: 12, color: 'black' },
                xanchor: 'left',
                yanchor: 'top'
            }
        ]
    };
    
    Plotly.newPlot('newtonPlot', [trace1, trace2, trace3, trace4], layout, plotConfig);
}

// 计算直线参数
async function calculateLineParameters() {
    // 检查是否有系数数据
    if (Object.keys(coefficients).length === 0) {
        showAlert('请先计算系数', 'warning');
        return;
    }

    // 获取当前的θ值（可能来自迭代结果或初始值）
    let thetaToUse = currentTheta;

    // 如果没有进行过迭代，使用初始θ值
    if (iterationResults.length === 0) {
        const initialThetaInput = document.getElementById('initialTheta');
        if (initialThetaInput && initialThetaInput.value) {
            thetaToUse = parseFloat(initialThetaInput.value);
            currentTheta = thetaToUse; // 更新currentTheta
        } else {
            showAlert('请设置初始θ值或完成牛顿迭代', 'warning');
            return;
        }
    }

    // 检查theta值是否在第一象限（仅警告，不阻止计算）
    let warningMessage = '';
    if (thetaToUse <= 0 || thetaToUse >= Math.PI / 2) {
        warningMessage = '注意：θ值超出第一象限范围（0 < θ < π/2），计算结果可能需要谨慎解释。';
    }

    try {
        const response = await fetch('/api/calculate_line_parameters', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                current_theta: thetaToUse  // 传递要使用的theta值
            })
        });

        const result = await response.json();

        if (result.success) {
            lineParameters = result.line_params;
            displayLineParameters();

            // 根据是否有警告信息决定显示内容和类型
            if (warningMessage) {
                showAlert(`直线参数计算完成 (使用θ = ${currentTheta.toFixed(6)})。${warningMessage}`, 'warning');
            } else {
                showAlert(`直线参数计算完成 (使用θ = ${currentTheta.toFixed(6)})`, 'success');
            }
            updateProgress(100);
        } else {
            showAlert(result.error, 'danger');
        }
    } catch (error) {
        showAlert('计算直线参数时发生错误: ' + error.message, 'danger');
    }
}

// 显示直线参数结果
function displayLineParameters() {
    const resultDiv = document.getElementById('lineParametersResult');
    resultDiv.innerHTML = `
        <h6>计算结果:</h6>
        <div class="row">
            <div class="col-md-6">
                <p><strong>b:</strong> ${lineParameters.b.toFixed(6)}</p>
                <p><strong>斜率 m:</strong> ${lineParameters.slope.toFixed(6)}</p>
                <p><strong>截距 c:</strong> ${lineParameters.intercept.toFixed(6)}</p>
            </div>
            <div class="col-md-6">
                <p><strong>θ (弧度):</strong> ${lineParameters.theta_radians.toFixed(6)}</p>
                <p><strong>θ (角度):</strong> ${lineParameters.theta_degrees.toFixed(2)}°</p>
            </div>
        </div>
        <div class="mt-3">
            <h6>直线方程:</h6>
            <p><strong>y = ${lineParameters.slope.toFixed(6)}x + ${lineParameters.intercept.toFixed(6)}</strong></p>
        </div>
    `;

    // 更新莫尔圆图，添加包络线
    updateMohrCirclePlot();
}

// 工具函数
function showAlert(message, type) {
    // 创建并显示Bootstrap警告框
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.insertBefore(alertDiv, document.body.firstChild);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 3000);
}

function clearInputFields() {
    document.getElementById('circleX').value = '';
    document.getElementById('circleY').value = '';
    document.getElementById('circleR').value = '';
    document.getElementById('confiningPressure').value = '';
    document.getElementById('compressiveStrength').value = '';
}

function clearResults() {
    document.getElementById('coefficientsResult').innerHTML = '<h6>计算结果将在此显示</h6>';
    document.getElementById('iterationTableBody').innerHTML = '';
    document.getElementById('lineParametersResult').innerHTML = '<h6>计算结果将在此显示</h6>';
    Plotly.purge('newtonPlot');
}

function updateProgress(percentage) {
    const progressBar = document.getElementById('progressBar');
    progressBar.style.width = percentage + '%';
}

function initializePlots() {
    // 初始化空的图表
    Plotly.newPlot('mohrCirclePlot', [], {
        title: '莫尔圆图',
        xaxis: { title: 'σ (MPa)' },
        yaxis: { title: 'τ (MPa)' },
        font: { family: 'SimSun, serif', size: 12 },
        margin: { t: 60, b: 60, l: 70, r: 30 },
        height: 600
    }, plotConfig);
}

// 导出图片功能
function exportPlot(format) {
    if (currentData.length === 0) {
        showAlert('没有数据可导出', 'warning');
        return;
    }

    // 获取导出选项
    const includeEnvelope = document.getElementById('includeEnvelope').checked;
    const includeLegend = document.getElementById('includeLegend').checked;

    // 构建URL参数
    const params = new URLSearchParams({
        include_envelope: includeEnvelope,
        include_legend: includeLegend
    });

    // 使用服务器端导出
    window.open(`/api/export_plot/${format}?${params.toString()}`, '_blank');
}

// 切换Auto模式
function toggleAutoMode() {
    autoMode = !autoMode;

    // 更新按钮显示
    const btn1 = document.getElementById('autoModeBtn');
    const btn2 = document.getElementById('autoModeBtn2');
    const text1 = document.getElementById('autoModeText');
    const text2 = document.getElementById('autoModeText2');

    if (autoMode) {
        if (btn1) {
            btn1.className = 'btn btn-success ms-2';
            text1.textContent = 'Auto (开)';
        }
        if (btn2) {
            btn2.className = 'btn btn-success ms-2';
            text2.textContent = 'Auto (开)';
        }
    } else {
        if (btn1) {
            btn1.className = 'btn btn-secondary ms-2';
            text1.textContent = 'Auto (关)';
        }
        if (btn2) {
            btn2.className = 'btn btn-secondary ms-2';
            text2.textContent = 'Auto (关)';
        }
    }
}

// 添加键盘事件支持
document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        const activeElement = document.activeElement;

        // 在圆数据输入框中按回车
        if (activeElement.id === 'circleR') {
            addManualData();
        }
        // 在实验数据输入框中按回车
        else if (activeElement.id === 'compressiveStrength') {
            addManualData();
        }
        // 在牛顿迭代参数中按回车
        else if (activeElement.id === 'precision') {
            solveNewton();
        }
    }
});
